"use client";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; // 添加ToggleGroup导入
import { useState, useEffect } from "react";
import { Asset, Host, getAssets, getHosts, createAsset, updateAsset, deleteAsset } from "@/lib/api";
import { useRouter } from "next/navigation";
import { 
  PlusIcon, 
  EyeIcon, 
  ServerIcon, 
  ActivityIcon, 
  SaveIcon, 
  XIcon, 
  TrashIcon,
  ListIcon,
  GridIcon,
  CalendarIcon
} from "lucide-react";
import { DataTable } from "@/components/ui/data-table/data-table";
import { assetColumns } from "@/app/assets/columns";
import React from "react";

export default function AssetsPage() {
  const router = useRouter();
  const [assets, setAssets] = useState<Asset[]>([]);
  const [hosts, setHosts] = useState<Host[]>([]);
  const [loading, setLoading] = useState(true);
  const [hostsLoading, setHostsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [formData, setFormData] = useState({
    name: "",
    asset_number: "",
    status: "idle",
    host: ""
  });
  const [editingAsset, setEditingAsset] = useState<Asset | null>(null);
  const [deletingAsset, setDeletingAsset] = useState<Asset | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [viewMode, setViewMode] = useState<"list" | "card">("list"); // 添加显示模式状态
  const itemsPerPage = 10;

  // Fetch hosts from backend
  const fetchHosts = async () => {
    try {
      setHostsLoading(true);
      const data = await getHosts();
      setHosts(data.results);
    } catch (err) {
      console.error("Failed to fetch hosts", err);
    } finally {
      setHostsLoading(false);
    }
  };

  useEffect(() => {
    fetchHosts();
  }, []);

  // 使用 useCallback 缓存 fetchAssets 函数，避免在每次渲染时重新创建
  const fetchAssets = React.useCallback(async (page: number = 1, search: string = searchTerm) => {
    try {
      setLoading(true);
      const params: Record<string, string> = {
        page: page.toString(),
        page_size: itemsPerPage.toString()
      };
      
      // 只有当搜索词非空时才添加搜索参数
      if (search) {
        params.search = search;
      }
      
      const data = await getAssets(params);
      setAssets(data.results);
      setTotalCount(data.count);
      setTotalPages(Math.ceil(data.count / itemsPerPage));
      setError(null);
    } catch (err) {
      setError("Failed to fetch assets");
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [searchTerm, itemsPerPage]); // 添加必要的依赖项

  useEffect(() => {
    fetchAssets(currentPage, searchTerm);
  }, [currentPage, searchTerm, fetchAssets]);

  const handleCreateAsset = async (event: React.FormEvent) => {
    event.preventDefault();
    try {
      await createAsset({
        name: formData.name,
        asset_number: formData.asset_number,
        status: formData.status,
        host: formData.host && formData.host !== "none" ? parseInt(formData.host.toString()) : null,
        host_info: null
      });
      
      setIsDialogOpen(false);
      // Reset form
      setFormData({
        name: "",
        asset_number: "",
        status: "idle",
        host: ""
      });
      setEditingAsset(null);
      // Refresh the asset list
      fetchAssets(currentPage, searchTerm);
    } catch (err) {
      console.error("Failed to create asset", err);
    }
  };

  const handleEditAsset = (asset: Asset) => {
    setEditingAsset(asset);
    setFormData({
      name: asset.name,
      asset_number: asset.asset_number,
      status: asset.status,
      host: asset.host ? asset.host.toString() : "none"
    });
    setIsDialogOpen(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [id]: value
    }));
  };

  const handleSelectChange = (value: string, name: string) => {
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (editingAsset) {
      // Update existing asset
      try {
        const updatedAsset = await updateAsset(editingAsset.asset_number, {
          name: formData.name,
          status: formData.status,
          host: formData.host && formData.host !== "none" ? parseInt(formData.host.toString()) : null
        });
        
        // Update asset in the list
        setAssets(prev => prev.map(asset => 
          asset.asset_number === updatedAsset.asset_number ? updatedAsset : asset
        ));
        
        setIsDialogOpen(false);
        setEditingAsset(null);
        setFormData({
          name: "",
          asset_number: "",
          status: "idle",
          host: ""
        });
      } catch (err) {
        console.error("Failed to update asset", err);
        // 可以添加一个用户友好的错误提示
        alert("Failed to update asset. Please check the console for details.");
      }
    } else {
      // Create new asset
      await handleCreateAsset(e);
    }
  };

  const confirmDeleteAsset = (asset: Asset) => {
    setDeletingAsset(asset);
    setIsDeleteDialogOpen(true);
  };

  const handleDeleteAsset = async () => {
    if (!deletingAsset) return;
    
    try {
      await deleteAsset(deletingAsset.asset_number);
      // Remove asset from the list
      setAssets(prev => prev.filter(asset => asset.asset_number !== deletingAsset.asset_number));
      setIsDeleteDialogOpen(false);
      setDeletingAsset(null);
      // Refresh the asset list
      fetchAssets(currentPage);
    } catch (err) {
      console.error("Failed to delete asset", err);
    }
  };

  const columns = assetColumns(handleEditAsset, confirmDeleteAsset);

  // 修复搜索功能被清空的问题
  const handleSearch = React.useCallback((value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  }, []);

  const handleViewAsset = (asset: Asset) => {
    router.push(`/assets/${asset.asset_number}`);
  };

  // 创建卡片视图组件
  const AssetCard = ({ asset }: { asset: Asset }) => (
    <Card 
      className="hover:shadow-md transition-shadow cursor-pointer" 
      onClick={() => handleViewAsset(asset)}
    >
      <CardHeader className="pb-2">
        <div className="flex justify-between items-start">
          <CardTitle className="text-lg">{asset.name}</CardTitle>
          <Badge 
            variant={
              asset.status === "active" ? "default" : 
              asset.status === "maintenance" ? "secondary" : "destructive"
            }
          >
            {asset.status.charAt(0).toUpperCase() + asset.status.slice(1)}
          </Badge>
        </div>
        <CardDescription className="text-sm">{asset.asset_number}</CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-2">
          <div className="flex items-center text-sm">
            <ServerIcon className="h-4 w-4 mr-2 text-muted-foreground" />
            <span>
              {asset.host_info 
                ? `${asset.host_info.hostname} (${asset.host_info.ip_address})` 
                : "No host assigned"}
            </span>
          </div>
          <div className="flex items-center text-sm">
            <CalendarIcon className="h-4 w-4 mr-2 text-muted-foreground" />
            <span>
              Created: {new Date(asset.created_time).toLocaleDateString()}
            </span>
          </div>
        </div>
      </CardContent>
    </Card>
  );

  if (loading) {
    return (
      <div className="container mx-auto py-10">
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl font-bold">Assets</CardTitle>
            <CardDescription>Loading assets...</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {[1, 2, 3, 4, 5].map((item) => (
                <div key={item} className="h-16 bg-gray-200 rounded animate-pulse"></div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto py-10">
        <Card className="max-w-2xl mx-auto">
          <CardHeader>
            <CardTitle className="text-3xl font-bold">Assets</CardTitle>
            <CardDescription className="text-red-500">{error}</CardDescription>
          </CardHeader>
          <CardContent>
            <p className="text-muted-foreground">Failed to load assets. Please try again later.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-10">
      <Card>
        <CardHeader>
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
              <CardTitle className="text-3xl font-bold">Assets</CardTitle>
              <CardDescription>Manage your infrastructure assets</CardDescription>
            </div>
            <div className="flex flex-col sm:flex-row gap-2">
              <ToggleGroup 
                type="single" 
                value={viewMode} 
                onValueChange={(value) => value && setViewMode(value as "list" | "card")}
                className="justify-start"
                variant="outline"
              >
                <ToggleGroupItem 
                  value="list" 
                  aria-label="List view"
                  className="data-[state=on]:bg-primary data-[state=on]:text-primary-foreground"
                >
                  <ListIcon className="h-4 w-4" />
                </ToggleGroupItem>
                <ToggleGroupItem 
                  value="card" 
                  aria-label="Card view"
                  className="data-[state=on]:bg-primary data-[state=on]:text-primary-foreground"
                >
                  <GridIcon className="h-4 w-4" />
                </ToggleGroupItem>
              </ToggleGroup>
              <Button onClick={() => setIsDialogOpen(true)} className="bg-primary hover:bg-primary/90">
                <PlusIcon />
                Add New Asset
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {viewMode === "list" ? (
            <DataTable 
              columns={columns} 
              data={assets} 
              searchField="name"
              onSearch={handleSearch}
              onRowClick={handleViewAsset}
            />
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {assets.map((asset) => (
                <AssetCard key={asset.asset_number} asset={asset} />
              ))}
            </div>
          )}
        </CardContent>
      </Card>
      
      {/* Add/Edit Asset Dialog */}
      {isDialogOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <div className="bg-background rounded-lg border p-6 w-full max-w-md">
            <div className="space-y-4">
              <div>
                <h3 className="text-lg font-semibold">
                  {editingAsset ? "Edit Asset" : "Add New Asset"}
                </h3>
                <p className="text-sm text-muted-foreground">
                  {editingAsset 
                    ? "Update the details below to edit the asset." 
                    : "Fill in the details below to add a new asset to the system."}
                </p>
              </div>
              <form className="space-y-4" onSubmit={handleSubmit}>
                <div className="space-y-2">
                  <Label htmlFor="name">Asset Name</Label>
                  <Input 
                    id="name" 
                    placeholder="Enter asset name" 
                    value={formData.name}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                {!editingAsset && (
                  <div className="space-y-2">
                    <Label htmlFor="asset_number">Asset Number</Label>
                    <Input 
                      id="asset_number" 
                      placeholder="Enter asset number" 
                      value={formData.asset_number}
                      onChange={handleInputChange}
                      required
                      readOnly={!!editingAsset}
                    />
                  </div>
                )}
                <div className="space-y-2">
                  <Label htmlFor="status">Status</Label>
                  <Select 
                    value={formData.status}
                    onValueChange={(value) => handleSelectChange(value, "status")}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="idle">Idle</SelectItem>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="maintenance">Maintenance</SelectItem>
                      <SelectItem value="faulty">Faulty</SelectItem>
                      <SelectItem value="retired">Retired</SelectItem>
                    </SelectContent>

                  </Select>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="host">Assigned Host</Label>
                  <Select
                    value={formData.host ? formData.host.toString() : "none"}
                    onValueChange={(value) => handleSelectChange(value === "none" ? "" : value, "host")}
                    disabled={hostsLoading}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select host" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">No host assigned</SelectItem>
                      {hosts.map((host) => (
                        <SelectItem key={host.id} value={host.id.toString()}>
                          {host.hostname} ({host.ip_address})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex justify-end space-x-2">
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={() => {
                      setIsDialogOpen(false);
                      setEditingAsset(null);
                      setFormData({
                        name: "",
                        asset_number: "",
                        status: "idle",
                        host: ""
                      });
                    }}
                  >
                    <XIcon className="h-4 w-4" />
                    Cancel
                  </Button>
                  <Button type="submit">
                    <SaveIcon className="h-4 w-4" />
                    {editingAsset ? "Update Asset" : "Add Asset"}
                  </Button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Dialog */}
      {isDeleteDialogOpen && deletingAsset && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <div className="bg-background rounded-lg border p-6 w-full max-w-md">
            <div className="space-y-4">
              <div>
                <h3 className="text-lg font-semibold">Confirm Deletion</h3>
                <p className="text-sm text-muted-foreground">
                  Are you sure you want to delete the asset "{deletingAsset.name}"? This action cannot be undone.
                </p>
              </div>
              <div className="flex justify-end space-x-2">
                <Button 
                  type="button" 
                  variant="outline" 
                  onClick={() => {
                    setIsDeleteDialogOpen(false);
                    setDeletingAsset(null);
                  }}
                >
                  Cancel
                </Button>
                <Button 
                  type="button" 
                  variant="destructive" 
                  onClick={handleDeleteAsset}
                  className="bg-destructive hover:bg-destructive/90"
                >
                  <TrashIcon className="h-4 w-4 mr-2" />
                  Delete Asset
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}